<?php
namespace App\Services;

class JSSDK {
    private string $appId;
    private string $appSecret;

    public function __construct() {
        $this->appId = config('wxpay.mpid');
        $this->appSecret = config('wxpay.mpsecret');
    }

    public function getSignPackage($url) {
        $jsapiTicket = $this->getJsApiTicket();
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string,
            "jsApiList" =>[
                'chooseImage',
                'previewImage',
                'getLocalImgData',
                'scanQRCode'
            ]
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
            $accessToken = Wechat::getMpToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
            $data['type'] = 'jsapi';
            $data['access_token'] = $accessToken;
            $ticket = Wechat::curlGet($url,$data);
            $ticket = json_decode($ticket,true);

//            $ticket = $res->ticket;
//            if ($ticket) {
//                $data = new stdClass();
//                $data->expire_time = time() + 4000;
//                $data->jsapi_ticket = $ticket;
//                file_put_contents($file, json_encode($data));
//            }
        return $ticket['ticket'];
    }



    private function httpGet($url) {
        return Wechat::curlGet($url);
    }
}
